package com.power.sifa.statistics.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.YesNo;
import com.plf.common.exception.BusinessException;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.approve.model.Apl_admreview;
import com.power.sifa.approve.model.Apl_main;
import com.power.sifa.approve.model.enumeration.St_apply;
import com.power.sifa.approve.model.enumeration.Tp_admpr;
import com.power.sifa.approve.model.enumeration.Tp_applysource;
import com.power.sifa.approve.model.enumeration.Tp_decisionEnum;
import com.power.sifa.approve.service.Apl_admreviewService;
import com.power.sifa.approve.service.Apl_mainService;
import com.power.sifa.approve.service.Apl_targetService;
import com.power.sifa.respond.model.Apl_respond;
import com.power.sifa.respond.model.enumeration.Tp_casetype;
import com.power.sifa.respond.service.Apl_respondService;
import com.power.sifa.statistics.model.pageInfo.StatisticsInfo;
import com.power.sifa.statistics.model.vo.BaseCountVO;
import com.power.sifa.statistics.model.vo.BaseGraphVO;
import com.power.sifa.statistics.service.Apl_statisticService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName Apl_statisticServiceImpl
 * @Author xiongzw
 * @Date 2023/11/3 9:10
 * @Description 首页统计service
 * @Version: 1.0
 **/
@Slf4j
@Service
public class Apl_statisticServiceImpl extends BaseServiceImpl implements Apl_statisticService {


    @Autowired
    private Apl_admreviewService apl_admreviewService;

    @Autowired
    private Apl_targetService apl_targetService;

    @Autowired
    private Apl_mainService apl_mainService;

    @Autowired
    private Apl_respondService apl_respondService;


    /**
     * 首页统计-统计行政行为的柱状图
     *
     * @return
     * @throws BusinessException
     */
    @Override
    public BaseGraphVO countPrtypeList(StatisticsInfo info) throws BusinessException {
        List<Apl_admreview> admreviewList = apl_admreviewService.findAllEndedList();
        if (CollectionUtil.isNotEmpty(admreviewList)) {
            try {
                // 统计对应的类别
                List<Tp_admpr> admprList = Arrays.asList(Tp_admpr.values());
                List<String> columnsList = admprList.stream().map(Tp_admpr::getDescription).collect(Collectors.toList());
                columnsList.add(0, "行政不作为");
                List<Long> dataList = new ArrayList<>();
                // 分类：分出两类： 行政不作为和非行政不作为
                // 行政不作为
                List<Apl_admreview> unActiveList = admreviewList.stream().filter(item -> ObjectUtil.isNotEmpty(item.getIsomission()) && item.getIsomission().equals(YesNo.YES) && (StringUtils.isNotEmpty(info.getAcceptadid()) ? info.getAcceptadid().equals(item.getMgradid()) : true)).collect(Collectors.toList());
                // 非行政不作为
                List<Apl_admreview> activeList = admreviewList.stream().filter(item -> ObjectUtil.isNotEmpty(item.getIsomission()) && item.getIsomission().equals(YesNo.NO) && (StringUtils.isNotEmpty(info.getAcceptadid()) ? info.getAcceptadid().equals(item.getMgradid()) : true)).collect(Collectors.toList());

                // 行政不作为
                dataList.add(CollectionUtil.isNotEmpty(unActiveList) ? unActiveList.size() : 0L);

                // 非行政不作为
                admprList.stream().forEach(item -> {
                    Long count = activeList.stream().filter(v -> item.getKey().equals(v.getPrtype())).count();
                    dataList.add(count);
                });


                BaseGraphVO result = BaseGraphVO.builder().columnList(columnsList).valueList(dataList).build();
                result.sort();
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e.getMessage());
                throw new BusinessException("统计数据报错");
            }

        }
        return new BaseGraphVO();
    }

    /**
     * 首页统计-统计决定类型
     *
     * @return
     * @throws BusinessException
     */
    @Override
    public BaseGraphVO countDecisionType(StatisticsInfo info) throws BusinessException {
        List<Apl_admreview> admreviewList = apl_admreviewService.findAllEndedList();
        if (CollectionUtil.isNotEmpty(admreviewList)) {
            // 按地区筛选
//            if (StringUtils.isNotEmpty(info.getAcceptadid())) {
//                admreviewList = admreviewList.stream().filter(item ->
//                        info.getAcceptadid().equals(item.getMgradid())
//                ).collect(Collectors.toList());
//            }
            try {
                // 统计对应的决定类型
                List<Tp_decisionEnum> admprList = Arrays.asList(Tp_decisionEnum.values());
                List<String> columnsList = admprList.stream().map(Tp_decisionEnum::getName).collect(Collectors.toList());
                List<Long> dataList = new ArrayList<>();
                // 过滤掉非空的数据
                admprList.stream().forEach(v -> {
                    Long count = admreviewList.stream().filter(item -> ObjectUtil.isNotEmpty(item.getDecisiontype()) && item.getDecisiontype().equals(v.getId())).count();
                    dataList.add(count);
                });


                BaseGraphVO result = BaseGraphVO.builder().columnList(columnsList).valueList(dataList).build();
                result.sort();
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e.getMessage());
                throw new BusinessException("统计决定类型报错");
            }

        }
        return new BaseGraphVO();
    }

    /**
     * 首页统计-统计被申请人前10的数据
     *
     * @return
     * @throws BusinessException
     */
    @Override
    public BaseGraphVO countTargetTop(StatisticsInfo info) throws BusinessException {
        List<Apl_admreview> admreviewList = apl_admreviewService.findAllEndedList();
        if (CollectionUtil.isNotEmpty(admreviewList)) {
            // 按地区筛选
            if (StringUtils.isNotEmpty(info.getAcceptadid())) {
                admreviewList = admreviewList.stream().filter(item -> info.getAcceptadid().equals(item.getMgradid())).collect(Collectors.toList());
            }
            try {
                List<String> applyids = admreviewList.stream().map(Apl_admreview::getId).collect(Collectors.toList());
                // 统计被申请人前10的数据
                List<Map<String, Object>> countResult = apl_targetService.countTargetTop10(applyids);
                List<String> columnsList = new ArrayList<>();
                List<Long> dataList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(countResult)) {
                    countResult.stream().forEach(element -> {
                        columnsList.add(ObjectUtil.isNotEmpty(element.get("name")) ? element.get("name").toString() : "");
                        dataList.add(ObjectUtil.isNotEmpty(element.get("count")) ? Long.parseLong(element.get("count").toString()) : 0L);
                    });

                }
                BaseGraphVO result = BaseGraphVO.builder().columnList(columnsList).valueList(dataList).build();
                result.sort();
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e.getMessage());
                throw new BusinessException("统计决定类型报错");
            }

        }
        return new BaseGraphVO();
    }


    /**
     * 大屏统计-统计案件状态
     *
     * @return
     * @throws BusinessException
     */
    @Override
    public List<BaseCountVO> countCaseStatus(StatisticsInfo info) throws BusinessException {
        // 统计审理中
        Long processingCount = this.apl_admreviewService.countPorcessingCaseStatus(info);
        // 统计已审结- 只有为已归档状态为已审结
        Long endedCount = this.apl_admreviewService.countEndedCaseStatus(info.getAcceptadid());
        // 统计中止状态
        Long suspendCount = this.apl_admreviewService.countSuspendCaseStatus(info.getAcceptadid());

        BaseCountVO processingVO = new BaseCountVO("processingStatus", "审理中", processingCount);
        BaseCountVO endedVO = new BaseCountVO("endedStatus", "已审结", endedCount);
        BaseCountVO suspendVO = new BaseCountVO("suspendStatus", "中止状态", suspendCount);

        List<BaseCountVO> result = new ArrayList<>();
        result.add(processingVO);
        result.add(endedVO);
        result.add(suspendVO);
        return result;
    }

    /**
     * @return
     * @throws BusinessException
     */
    @Override
    public List<BaseCountVO> countCaseChangeYear(StatisticsInfo info) throws BusinessException {
        List<BaseCountVO> result = new ArrayList<>();
        // 统计申请类型的值
        List<Apl_main> allMainList = this.apl_mainService.findAll();
        if (CollectionUtil.isNotEmpty(allMainList)) {
            // 线下录入
            Long offlineRecord = allMainList.stream().filter(element -> ObjectUtil.isNotNull(element.getSource()) && element.getSource().equals(Tp_applysource.CASEREG) && (StringUtils.isNotEmpty(info.getAcceptadid()) ? info.getAcceptadid().equals(element.getAcceptadid()) : true)).count();
            // 网上申请
            Long internetRecord = allMainList.stream().filter(element -> ObjectUtil.isNotNull(element.getSource()) && element.getSource().equals(Tp_applysource.INTERNET) && (StringUtils.isNotEmpty(info.getAcceptadid()) ? info.getAcceptadid().equals(element.getAcceptadid()) : true)).count();
            result.add(new BaseCountVO("offlineRecord", "线下录入", offlineRecord));
            result.add(new BaseCountVO("internetRecord", "网上申请", internetRecord));

            // 统计月度增长的值
            // 过滤当月的值
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDate nowTime = LocalDate.now();
            LocalDate lastMonthTime = LocalDate.now().plusMonths(-1);
            Long nowMonthRecord = allMainList.stream().filter(element -> ObjectUtil.isNotNull(element.getCreatetime()) && (StringUtils.isNotEmpty(info.getAcceptadid()) ? info.getAcceptadid().equals(element.getAcceptadid()) : true)).filter(element -> {
                LocalDate createTime = LocalDate.parse(element.getCreatetime(), formatter);
                return createTime.getMonthValue() == nowTime.getMonthValue();
            }).count();

            // 过滤上月的值
            Long lastMonthRecord = allMainList.stream().filter(element -> ObjectUtil.isNotNull(element.getCreatetime()) && (StringUtils.isNotEmpty(info.getAcceptadid()) ? info.getAcceptadid().equals(element.getAcceptadid()) : true)).filter(element -> {
                LocalDate createTime = LocalDate.parse(element.getCreatetime(), formatter);
                return createTime.getMonthValue() == lastMonthTime.getMonthValue();
            }).count();
            result.add(new BaseCountVO("nowMonthRecord", "当月统计", nowMonthRecord));
            result.add(new BaseCountVO("lastMonthRecord", "上月统计", lastMonthRecord));
            // 统计年度增长的值
            Long nowYearRecord = allMainList.stream().filter(element -> ObjectUtil.isNotNull(element.getCreatetime()) && (StringUtils.isNotEmpty(info.getAcceptadid()) ? info.getAcceptadid().equals(element.getAcceptadid()) : true)).filter(element -> {
                LocalDate createTime = LocalDate.parse(element.getCreatetime(), formatter);
                return createTime.getYear() == nowTime.getYear();
            }).count();

            // 过滤上年的值
            LocalDate lastYearTime = LocalDate.now().plusYears(-1);
            Long lastYearRecord = allMainList.stream().filter(element -> ObjectUtil.isNotNull(element.getCreatetime()) && (StringUtils.isNotEmpty(info.getAcceptadid()) ? info.getAcceptadid().equals(element.getAcceptadid()) : true)).filter(element -> {
                LocalDate createTime = LocalDate.parse(element.getCreatetime(), formatter);
                return createTime.getYear() == lastYearTime.getYear();
            }).count();

            result.add(new BaseCountVO("nowYearRecord", "当年统计", nowYearRecord));
            result.add(new BaseCountVO("lastYearRecord", "上年统计", lastYearRecord));
        }
        return result;
    }

    /**
     * 大屏统计-统计行政应诉案件
     *
     * @return
     * @throws BusinessException
     */

    @Override
    public List<BaseCountVO> CountRespondCase() throws BusinessException {
        List<BaseCountVO> result = new ArrayList<>();
        // 统计结果：
        BaseCountVO processingCase = new BaseCountVO("processingCase", "审理中", 0L);
        BaseCountVO endCase = new BaseCountVO("endCase", "已审结", 0L);
        BaseCountVO firstCase = new BaseCountVO("firstCase", "一审", 0L);
        BaseCountVO secondCase = new BaseCountVO("secondCase", "二审", 0L);
        BaseCountVO retrialCase = new BaseCountVO("retrialCase", "再审", 0L);

        // TODO: 后续统计审理中和已审结的案件
        // 查询全部的应诉的案件数据
        List<Apl_respond> respongCaseList = apl_respondService.findAll();
        if (CollectionUtil.isNotEmpty(respongCaseList)) {
            Map<Integer, List<Apl_respond>> respondCaseMap = respongCaseList.stream().filter(el -> ObjectUtil.isNotNull(el.getCasetype())).collect(Collectors.groupingBy(Apl_respond::getCasetype));
            for (Integer key : respondCaseMap.keySet()) {
                switch (key) {
                    case Tp_casetype.FIRSTINSTANCE:
                        firstCase.setCount(respondCaseMap.get(key).stream().count());
                        break;
                    case Tp_casetype.SECONDINSTANCE:
                        secondCase.setCount(respondCaseMap.get(key).stream().count());
                        break;
                    case Tp_casetype.RETRIAL:
                        retrialCase.setCount(respondCaseMap.get(key).stream().count());
                        break;
                    default:
                        break;
                }
            }
        }
        result.add(processingCase);
        result.add(endCase);
        result.add(firstCase);
        result.add(secondCase);
        result.add(retrialCase);

        return result;
    }

    /**
     * 复议情况案件统计
     *
     * @param info
     * @return
     * @throws BusinessException
     */
    @Override
    public Map<String, Object> countFinish(StatisticsInfo info) throws BusinessException {

        // 统计审理中
        Long underTrialNum = this.apl_admreviewService.countPorcessingCaseStatus(info);
        BaseCountVO underTrial = new BaseCountVO("underTrial", "审理中", underTrialNum);

        // 获取本年各个月份已审计案件数量
        List<Apl_main> listByStatus = this.apl_mainService.getListByStatus(St_apply.COMPLETELIST);
        List<Apl_main> collection = listByStatus;
        if (info.getAcceptadid() != null && !info.getAcceptadid().isEmpty()) {
            collection = listByStatus.stream()
                    .filter(aplMain -> info.getAcceptadid().equals(aplMain.getAcceptadid()))
                    .collect(Collectors.toList());
        }
        // 创建一个Map来统计各个月份的数量
        Map<Integer, Integer> monthlyCount = new HashMap<>();
        for (int i = 1; i <= 12; i++) {
            monthlyCount.put(i, 0);
        }

        // 遍历列表，统计各个月份的数量
        for (Apl_main aplMain : collection) {
            String finishtime = aplMain.getFinishtime(); // 假设这是获取 finishtime 的方法

            // 将字符串解析为日期对象
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime dateTime = LocalDateTime.parse(finishtime, formatter);
            LocalDate date = dateTime.toLocalDate();

            // 提取年份和月份信息
            int year = date.getYear();

            if (!String.valueOf(year).equals(info.getYear())) {
                continue;
            }

            int month = date.getMonthValue();

            // 更新Map中对应月份的数量
            monthlyCount.put(month, monthlyCount.getOrDefault(month, 0) + 1);
        }

        List<BaseCountVO> finishTrial = new ArrayList<>();
        // 打印统计结果
        for (Map.Entry<Integer, Integer> entry : monthlyCount.entrySet()) {
            finishTrial.add(BaseCountVO.builder()
                    .key(String.valueOf(entry.getKey()))
                    .name(getChineseMonthName(entry.getKey()))
                    .count(entry.getValue().longValue()).build());
        }

        // 结果封装
        Map<String, Object> result = new HashMap<>();
        result.put("underTrial", underTrial);
        result.put("finishTrial", finishTrial);
        return result;
    }

    /**
     * 行政复议案件情况
     *
     * @param info
     * @return
     * @throws BusinessException
     */
    @Override
    public PageDataResponse caseStatus(StatisticsInfo info) throws BusinessException {
//    public Map<String, List<BaseCountVO>> caseStatus(StatisticsInfo info) throws BusinessException {
//        Map<String, List<BaseCountVO>> map = new TreeMap<>(Comparator.reverseOrder());
        Map<String, List<BaseCountVO>> map = new TreeMap<>(Comparator.reverseOrder());
        List<BaseCountVO> baseCountVOList = this.apl_mainService.caseStatus(info.getAcceptadid());

        // 获取列表中的所有key
        List<String> allkeys = baseCountVOList.stream()
                .map(BaseCountVO::getKey) // 提取每个BaseCountVO对象的key属性
                .distinct() // 去重
                .collect(Collectors.toList());
        int start = (info.getPageNumber() - 1) * info.getPageSize();
        int end = Math.min(start + info.getPageSize(), allkeys.size());
        List<String> yearKeys = allkeys.subList(start, end);

        for (String year : yearKeys) {

            BaseCountVO received = BaseCountVO.builder().key("received").name("收到").count(0L).build();
            BaseCountVO accept = BaseCountVO.builder().key("accept").name("受理").count(0L).build();
            BaseCountVO premediation = BaseCountVO.builder().key("premediation").name("受前调解").count(0L).build();
            List<BaseCountVO> yearList = Arrays.asList(received, accept, premediation);

            List<BaseCountVO> baseCounts = baseCountVOList.stream()
                    .filter(baseCountVO -> baseCountVO.getKey().equals(year))
                    .collect(Collectors.toList());

            baseCounts.stream()
                    .filter(baseCountVO -> baseCountVO.getName().equals("收到"))
                    .findFirst()
                    .ifPresent(baseCountVO -> received.setCount(baseCountVO.getCount()));
            baseCounts.stream()
                    .filter(baseCountVO -> baseCountVO.getName().equals("受理"))
                    .findFirst()
                    .ifPresent(baseCountVO -> accept.setCount(baseCountVO.getCount()));
            baseCounts.stream()
                    .filter(baseCountVO -> baseCountVO.getName().equals("受前调解"))
                    .findFirst()
                    .ifPresent(baseCountVO -> premediation.setCount(baseCountVO.getCount()));
            map.put(year, yearList);
        }
        PageDataResponse pageResult = new PageDataResponse(Arrays.asList(map), Long.valueOf(allkeys.size()),
                info.getPageSize(), info.getPageNumber() <= 1 ? 1 : info.getPageNumber());
        return pageResult;
//        return map;
    }

    /**
     * 2023年月度收案情况
     *
     * @param info
     * @return
     * @throws BusinessException
     */
    @Override
    public Map<String, BaseGraphVO> caseReceptionStatus(StatisticsInfo info) throws BusinessException {
        List<BaseCountVO> baseCountVOList = this.apl_mainService.caseReceptionStatus(info.getAcceptadid(), info.getYear());

        String[] chineseMonths = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"};
        List<String> monthList = Arrays.asList(chineseMonths);

        Map<String, BaseGraphVO> map = new HashMap<>();
        map.put("receivedNum", new BaseGraphVO(monthList, new ArrayList<>(Collections.nCopies(12, 0L))));
        map.put("acceptedNum", new BaseGraphVO(monthList, new ArrayList<>(Collections.nCopies(12, 0L))));

        for (BaseCountVO baseCountVO : baseCountVOList) {
            String monthName = getChineseMonthName(Integer.parseInt(baseCountVO.getKey()));
            BaseGraphVO targetList = map.get(baseCountVO.getName());
            if (targetList != null && monthList.contains(monthName)) {
                int index = monthList.indexOf(monthName);
                targetList.getValueList().set(index, baseCountVO.getCount());
            }
        }

        return map;
    }

    @Override
    public BaseGraphVO countCaseType(StatisticsInfo info) throws BusinessException {
        return this.apl_mainService.countCaseType(info.getAcceptadid(), info.getYear());
    }

    @Override
    public List<BaseCountVO> countClosingType(StatisticsInfo info) throws BusinessException {
        return this.apl_mainService.countClosingType(info.getAcceptadid(), info.getYear());
    }

    @Override
    public Map<String, List<BaseCountVO>> countClosing(StatisticsInfo info) throws BusinessException {
        return this.apl_mainService.countClosing(info.getAcceptadid(), info.getYear());
    }

    /**
     * 大屏统计--收案数据统计
     *
     * @param info
     * @return
     * @throws BusinessException
     */
    @Override
    public List<BaseCountVO> countReceiptData(StatisticsInfo info) throws BusinessException {
        List<BaseCountVO> baseCountVOList = this.apl_mainService.countReceiptData(info.getAcceptadid());

        return baseCountVOList;
    }

    /**
     * 获取中文月份
     *
     * @param monthNumber
     * @return
     */
    public static String getChineseMonthName(int monthNumber) {
        String[] chineseMonths = {"一月", "二月", "三月", "四月", "五月", "六月",
                "七月", "八月", "九月", "十月", "十一月", "十二月"};
        if (monthNumber >= 1 && monthNumber <= 12) {
            return chineseMonths[monthNumber - 1];
        } else {
            return "无效的月份";
        }
    }

    /**
     * 获取前一年的年份
     *
     * @return
     */
    public static String getPreviousYear() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取前一年的年份
        return String.valueOf(currentDate.minusYears(1).getYear());
    }
}
